﻿(function (doc, win) {
    //  html
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            clientWidth = (clientWidth > 768) ? 768 : clientWidth; docEl.style.fontSize = clientWidth / 7.5 + 'px';
        };
    if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false);
    recalc();
})(document, window);
/**
* 自定义下拉框
* @param option
*/
function cusSelect(eleId, config = {}) {
    let option = Object.assign({}, { 
        selectTag: '',
        multi: false,//多选
        searchAjax: false,//搜索是否异步，请写异步获取数据方法
        selectFun: function () { },
        callback: function () { }
    }, config || {}), tplData = { title: option.title }, tpl = $("#script_cus_select").html();

    /**
     * 初始化
     */
    const init = function () {
        //初始化模板
        let tplc = tpl.replace(/\$\{(.*?)\}/i, function (match, $1) {
            return tplData[$1];
        });
        option.selectTag = `cusSelect_${eleId}`;
        $('#' + option.selectTag).remove();
        $('body').append(`<div id="${option.selectTag}">${tplc}</div>`);

        initData(option.data || []);
        bindEvent();
    };

    /**
     * 初始化数据
     */
    const initData = function (data = []) {
        if (data) {
            let str = '';
            $.each(data, function (index, item) {
                str += `<li class="option-list option-list-one" data="${item.text}|${item.id}|${index}" data-index="${index}" data-text="${item.text}" data-id="${item.id}">
								<span>${item.text}</span>
								<div class="checked"></div>
							</li>`;
            });
            $('#' + option.selectTag).find(".option-group-one").html(str);
        }
    };

    /**
     * 绑定事件
     */
    const bindEvent = function () {

        //显示
        $('#' + eleId).parent().on("click", function () {
            $("#" + option.selectTag + " #mymodal").show();
            $("#" + option.selectTag + " #mymodal").find(".modal-main").animate({ "bottom": "0" }, 400);

            if (option.multi !== undefined && option.multi) {
                if (option.multiSelectData) {
                    $("#" + option.selectTag).find(".option-list-one .checked").removeClass('active').hide();
                    option.multiSelectData.forEach(function (item, index) {
                        $("#" + option.selectTag).find(".option-list-one[data-id=" + item.id + "]").trigger('click');
                    });
                }
            }
        });

        //绑定搜索
        $("#" + option.selectTag).on('keyup', '.seach_name', function (e) { 
            let searchAjax = option.searchAjax || false, value = $(e.target).val().trim();
            if (searchAjax) {
                if (typeof searchAjax === 'function') {
                    let res = searchAjax.call(this, value);
                    if (res === false) return;
                    //重新加载数据
                    res && 'data' in res && initData(res.data);
                }
            } else {
                if (value.length < 1) {
                    $(this).next('ul').find('li').show();
                } else {
                    $(this).next('ul').find('li').hide();
                    $(this).next('ul').find("li[data*='" + value + "']").show();
                }
            }
        });

        //选择项点击
        $("#" + option.selectTag).on("click", ".option-list-one", function () {
            let index = $(this).index();

            //多选模式
            let data = [];
            if (option.multi !== undefined && option.multi) {
                let cIndex = 0;
                data = option.data[index];
                option.multiSelectDataT = option.multiSelectDataT || [];//临时属性，确定后会删除
                if (!option.multiSelectDataT.some((item, cindex) => {
                    cIndex = cindex;
                    return item.id == data.id;
                })) {
                    option.multiSelectDataT.push(data);
                    $(this).find('.checked').addClass('active').show();
                } else {
                    //多选至少保留一个
                    if (option.multiSelectDataT.length > 1) {
                        option.multiSelectDataT.splice(cIndex, 1);
                        $(this).find('.checked').removeClass('active').hide();
                    }
                }
                data = option.multiSelectDataT;
            } else {
                $(this).parent().find('.checked').removeClass('active').hide();
                $(this).find('.checked').addClass('active').show();
                data = option.data[index];
            }

            if (option.selectFun && typeof option.selectFun === 'function') {
                if (option.selectFun.call(this, data) === false) return;
            }
        });

        //点击关闭
        $("#" + option.selectTag).on("click", ".cancel", function () {
            $("#" + option.selectTag).find(".ensure").trigger("click")
            close();
        });

        //点击确定
        $("#" + option.selectTag).on("click", ".ensure", function (event) { 
            let checkIndex = $("#" + option.selectTag).find('.option-list-one .active').parent().index();
            let data = checkIndex >= 0 ? option.data[checkIndex] : []; 
            if (option.multi !== undefined && option.multi) data = option.multiSelectData = option.multiSelectDataT || [];

            if (option.callback && typeof option.callback === 'function') {
                if (option.callback.call(this, data) === false) return;
            }
            close();
        });
    };

    const close = function () {
        delete (option.multiSelectDataT);//删除临时属性
        $("#" + option.selectTag).find(".modal-main").animate({ "bottom": "-900px" }, 400);
        setTimeout(() => {
            $("#" + option.selectTag + " #mymodal").fadeOut();
        }, 350)
    };

    return { init, close };
}